package com.dmall.play.interview.chapter09;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Leetcode279V1 {

    public int numSquares(int n) {
        Deque<Integer> path = new ArrayDeque<>();
        List<List<Integer>> res = new ArrayList<>();
        backTrack(n, 1, path, res);
        int min = Integer.MAX_VALUE;
        for (List<Integer> re : res) {
            min = Math.min(min, re.size());
        }
        return min;
    }

    private void backTrack(int n, int start, Deque<Integer> path, List<List<Integer>> res) {
        if (n < 0) {
            return;
        } else if (n == 0) {
            res.add(new ArrayList<>(path));
        } else {
            int loopNum = (int) Math.ceil(Math.sqrt(n));
            for (int i = start; i <= loopNum; i++) {
                int square = i * i;
                path.add(square);
                backTrack(n - square, i, path, res);
                path.removeLast();
            }
        }
    }

    public static void main(String[] args) {
        Leetcode279V1 leetcode279 = new Leetcode279V1();
        System.out.println(leetcode279.numSquares(9));
    }
}
